package com.simon.jkxj.ui.diet;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.simon.jkxj.R;
import android.view.View;
import android.widget.ImageView;
import android.widget.Button;
import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.formatter.ValueFormatter;
import java.util.Calendar;
import java.util.List;
import android.app.AlertDialog;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class BloodSugarAddActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blood_sugar_add);
        ImageView btnBack = findViewById(R.id.btn_back);
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        Button btnAdd = findViewById(R.id.btn_add);
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText etBloodSugar = findViewById(R.id.et_blood_sugar);
                String valueStr = etBloodSugar.getText().toString();
                if (valueStr.isEmpty()) {
                    Toast.makeText(BloodSugarAddActivity.this, "请输入血糖值", Toast.LENGTH_SHORT).show();
                    return;
                }
                float value = Float.parseFloat(valueStr);
                long time = System.currentTimeMillis();
                Intent intent = new Intent();
                intent.putExtra("blood_sugar_value", value);
                intent.putExtra("blood_sugar_time", time);
                updateChart();
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        // 1. 日期和时间自动显示
        TextView tvDate = findViewById(R.id.tv_date);
        TextView tvTime = findViewById(R.id.tv_time);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
        String dateStr = dateFormat.format(new Date());
        String timeStr = timeFormat.format(new Date());
        tvDate.setText(dateStr);
        tvTime.setText(timeStr);
        // 2. 所属阶段选择
        TextView tvStage = findViewById(R.id.tv_stage);
        tvStage.setOnClickListener(v -> {
            String[] stages = {"凌晨", "空腹", "早餐后", "午餐前", "午餐后", "晚餐前", "晚餐后", "睡前"};
            new AlertDialog.Builder(this)
                .setTitle("请选择所属阶段")
                .setItems(stages, (dialog, which) -> tvStage.setText(stages[which]))
                .show();
        });
        // 3. 尿液选择
        TextView tvUrine = findViewById(R.id.tv_urine);
        tvUrine.setOnClickListener(v -> {
            String[] urines = {"50", "100", "150", "200", "250", "300", "350", "400", "450", "500"};
            new AlertDialog.Builder(this)
                .setTitle("请选择尿量")
                .setItems(urines, (dialog, which) -> tvUrine.setText(urines[which]))
                .show();
        });
        // 4. 次数选择
        TextView tvTimes = findViewById(R.id.tv_times);
        tvTimes.setOnClickListener(v -> {
            String[] times = {"1", "2", "3", "4", "5", "6", "7", "8"};
            new AlertDialog.Builder(this)
                .setTitle("请选择小便次数")
                .setItems(times, (dialog, which) -> tvTimes.setText(times[which]))
                .show();
        });
        updateChart();
    }

    private void updateChart() {
        List<BloodSugarRecordActivity.BloodSugarRecord> recordList = BloodSugarDataManager.getRecords();
        List<Entry> entries = new java.util.ArrayList<>();
        // 获取当天零点的时间戳
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        long todayZero = calendar.getTimeInMillis();
        for (int i = 0; i < recordList.size(); i++) {
            BloodSugarRecordActivity.BloodSugarRecord r = recordList.get(i);
            float hour = (r.time - todayZero) / (60f * 60f * 1000f);
            entries.add(new Entry(hour, r.value));
        }
        LineChart chart = findViewById(R.id.line_chart);
        if (entries.size() > 0) {
            LineDataSet dataSet = new LineDataSet(entries, "血糖");
            dataSet.setCircleRadius(5f);
            dataSet.setLineWidth(2f);
            dataSet.setColor(0xFF8BC34A);
            dataSet.setCircleColor(0xFF8BC34A);
            dataSet.setValueTextSize(12f);
            LineData lineData = new LineData(dataSet);
            chart.setData(lineData);
        } else {
            chart.clear();
        }
        XAxis xAxis = chart.getXAxis();
        xAxis.setAxisMinimum(0f);
        xAxis.setAxisMaximum(24f);
        xAxis.setLabelCount(7, true);
        xAxis.setGranularity(4f);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                int hour = (int) value;
                if (hour < 0) hour = 0;
                if (hour > 24) hour = 24;
                return String.format("%02d:00", hour);
            }
        });
        chart.getAxisLeft().setAxisMinimum(0f);
        chart.getAxisLeft().setAxisMaximum(20f);
        chart.getAxisLeft().setLabelCount(5, true);
        chart.getAxisRight().setEnabled(false);
        chart.invalidate();
    }
} 